/*
	Copyright (c) 2010 <copyright holders>
	This source code is licensed under The MIT License,
	see the file LICENSE for details.
	*/

#include "ClientLogic.hpp"

#include <boost/lexical_cast.hpp>

#include "gen/netmsg.pb.h"

namespace spelprog2 {
namespace net {
namespace client_logic {

using namespace netmsg;


void PassOn::onMessage(MessagePtr msg, const NetMessageInfo & info)
{
    client_.postMsg(msg, info);
}


void HandleLogin::onMessage(MessagePtr msg, const NetMessageInfo & info)
{
    assert(info.origin == SERVER_ID);

    LoginReply * const loginReply = dynamic_cast<LoginReply *>(msg.get());

    if (loginReply->accepted() && loginReply->has_assignedid()) {
        netlog << "Login accepted";

        UserId id = loginReply->assignedid();
        client_.setUserId(id);
        client_.getVars().addUser(id);
    }
    else {
        netlog << "Login rejected";

        client_.disconnect();
    }
}


void HandleVarChange::onMessage(MessagePtr msg, const NetMessageInfo & info)
{
    assert(info.origin == SERVER_ID);

    ServerVarChange * const varChange = dynamic_cast<ServerVarChange *>(msg.get());

    UserId id = varChange->userid();

    if (!client_.getVars().hasUser(id)) {
        netlog << "Warning, received netvar change to unknown user #" + boost::lexical_cast<std::string>(id);
        return;
    }

    client_.getVars().updateVar(id, varChange->key(), varChange->value());
}


void HandleUserChange::onMessage(MessagePtr msg, const NetMessageInfo & info)
{
    assert(info.origin == SERVER_ID);

    UserChange * const userChange = dynamic_cast<UserChange *>(msg.get());

    UserChangeAction action = userChange->action();
    UserId id = userChange->userid();

    if (action == ADD_USER) {
        client_.getVars().addUser(id);
    }
    else if (action == DELETE_USER) {
        client_.getVars().removeUser(id);
    }
}


}; //namespace client_logic
}; //namespace net
}; //namespace spelprog2
